/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    useTheme, Button, InputLine, Input, TextArea, SuffixInput, Layer, Popover, PopoverRefer, PopoverContent, PopoverDescription, MenuList,
    MenuItem, PopoverClose, IconX, Text, LineColumn, ButtonRefComp, IconButton, IconArchive, BlobInputList
} from "customize-easy-ui-component";
import {
    InspectRecordLayout, InternalItemProps,  useInputControlSure, useItemInputControl
} from "../../common/base";
import {EditStorageContext} from "../../StorageContext";
import {useDeleteAddSub} from "../../hook/useDeleteAddSub";
import {useMeasureInpFilter} from "../../common/hooks";
import {useUppyUpload} from "../../hook/useUppyUpload";

export const 结果打勾等的=['√','×','无此项','-'];
//公共的复用性好的组件；编辑、原始记录，在多数模板能通用的。不通用的要安排放在更加具体贴近的目录文件内。
//方便不同模板和不同版本的可重复引用。文件目录管理，组件按照抽象性程度和参数配置的关联度，分级分层次，标识容易区分开。
// http://localhost:8673/uploadTUS/  const uppy =new Uppy().use(Tus, { endpoint: 'https://tusd.tusdemo.net/files/', withCredentials:true });
// Don’t forget to keep the Uppy instance outside of your component. //new Uppy().use(Webcam);  //endpoint: 'https://tusd.tusdemo.net/files/'
// const uppy =new Uppy().use(Tus, { endpoint: 'https://tusd.tusdemo.net/files/' });     【文档】https://uppy.io/docs/react/   meta:{liveDays: 957,isp:'63990a43f-6e9e-498f-84b6-aff9d7e4b211'},
//注意：endpoint一定要和后端授权登录一样的才行，否则没有cookie。  metadata:{name: file.name,contentType: file.type || 'application/octet-stream',emptyMetaKey: ''}

export const itemA测点位置=['点图说明','_FILE_部位','检测结果','表面状况','实测点数','memo','测厚表']
export const Surface=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd, repId}:InternalItemProps,  ref
    ) => {
        const theme = useTheme();
        const {modified,setModified,} =React.useContext(EditStorageContext) as any;
        const [getInpFilter] = useMeasureInpFilter(null, itemA测点位置,);
        const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
        const onFinish = React.useCallback(async(upfile: any, del:boolean) => {
            //底下俩个变量不能够采用函数以外的，依赖出问题？？导致更新会不正常的。
            onSure({...inp, '_FILE_部位': upfile});
            !modified && setModified(true);
        }, [inp, modified,onSure,setModified]);
        const [uploadDom]=useUppyUpload({ repId:repId!,
            maxFile:1, onFinish, storeObj: inp?._FILE_部位
        });
        function onCalcPoint(){
            let cpsum=0;
            inp?.测厚表?.forEach((a: any, i:number)=> {
                if(a.vl1 && a.vl1!=='/') cpsum++;
                if(a.vl2 && a.vl2!=='/') cpsum++;
                if(a.vl3 && a.vl3!=='/') cpsum++;
                if(a.vl4 && a.vl4!=='/') cpsum++;
                if(a.vl5 && a.vl5!=='/') cpsum++;
                if(a.vl6 && a.vl6!=='/') cpsum++;
            });
            return cpsum;
        };

        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'测厚点位置示图'}>

                <InputLine  label='1、表面状况' >
                    <Input  value={inp?.表面状况 ||''}  placeholder="使用默认规则，缺省编号情况的可不填"
                            onChange={e => setInp({ ...inp, 表面状况: e.currentTarget.value||undefined}) } />
                </InputLine>
                <InputLine  label='2、实测点数' >
                    <SuffixInput value={ inp?.实测点数 || 0} component={Input}  type="number" placeholder="可点击自动计算"
                                 css={{  "div:has(&).SuffixInput_Top": { display: 'flex', alignItems: 'center' },
                                     "div:has(&).Input_Top": { width: "70%" },
                                     width: '100%',
                                 }}
                                 onChange={e=>{
                                     setInp({ ...inp, 实测点数: Number(e.currentTarget.value) || 0})
                                 } }
                    >个
                        <IconButton  variant="ghost"  icon={<IconArchive />}  label="默认"
                                     onClick={async (e) => {
                                         await setInp({ ...inp, 实测点数: onCalcPoint()})
                                     } }
                        />
                    </SuffixInput>
                </InputLine>

                <InputLine label='测厚点位置示图（文字说明）：'>
                    <BlobInputList value={inp?.点图说明 || ''}   datalist={["参考上面的位置示图","参考上面设备编号 的位置示图"]}
                                   onListChange={v => setInp({...inp, 点图说明: v || undefined}) } />
                </InputLine>
                测厚点位置示图：
                {uploadDom}

                备注:
                <TextArea  value={inp?.memo ||''} rows={4}
                           onChange={e => setInp({ ...inp, memo: e.currentTarget.value||undefined}) } />
                检测结果:
                <TextArea  value={inp?.检测结果 ||''} rows={4}
                           onChange={e => setInp({ ...inp, 检测结果: e.currentTarget.value||undefined}) } />
            </InspectRecordLayout>
        );
    } );


const checkConfig测量仪=[['测量仪器型号','仪器型号'],['测量仪器编号','仪器编号'],['测量仪器精度','仪器精度'],['耦合剂','耦合剂'],
    ['筒体','筒体名义'],['封头','封头名义'],['管箱（夹套）筒体','管筒体名义'],['管箱（夹套）封头','管封头名义'],
    ['筒体','筒体实测'],['封头','封头实测'],['管箱（夹套）筒体','管筒体实测'],['管箱（夹套）封头','管封头实测']];
export const Instrument=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd,verId,repId}:InternalItemProps,  ref
    ) => {
        const getInpFilter = React.useCallback((par: any) => {
            let fields={} as any;
            checkConfig测量仪.forEach(([ _,aName], i:number)=> {
                fields[aName] =par[aName];
            });
            return fields;
        }, []);
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        const {line}=useDeleteAddSub(nestMd!, redId!,verId!,repId!);
        const areaView=(start:number,end:number)=>{
          return checkConfig测量仪.map(([title,aName], i:number)=> {
                if(i>=start && i<=end)
                   return  <InputLine key={i} label={title+`:`}>
                            <Input  value={inp?.[aName] || ''}
                                    onChange={e => {
                                        inp[aName] = e.currentTarget.value||undefined;
                                        setInp({...inp});
                                    } } />
                        </InputLine>
            })
        };

        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'壁厚测定-测量仪器型号'} column={0}>
                {line}
                <LineColumn  key={1} column={2}>
                    { areaView(0,3) }
                </LineColumn>
                名义厚度<br/>
                <LineColumn  key={2} column={2}>
                   { areaView(4,7) }
                </LineColumn>
                实测最小壁厚<br/>
                <LineColumn  key={3} column={2}>
                   { areaView(8,20) }
                </LineColumn>
            </InspectRecordLayout>
        );
    } );


export const Measurement=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd}:InternalItemProps,  ref
    ) => {
        const getInpFilter = React.useCallback((par: any) => {
            const {测厚表} =par||{};
            return {测厚表};
        }, []);
        const {inp, setInp} = useItemInputControl({ ref });
        const [seq, setSeq] = React.useState<number | null>(null);   //表對象的當前一條。
        //复合型的状态管理做法。 多个字段聚合的；
        const [obj, setObj] = React.useState({no1:'',vl1:'',no2:'',vl2:'',no3:'',vl3:'',
            no4:'',vl4:'',no5:'',vl5:'',no6:'',vl6:''});
        React.useEffect(() => {
            let size =inp?.测厚表?.length;
            setSeq(size>0?  size-1:null);
        }, [inp]);
        function onModifySeq(idx:number,it:any){
            setObj(it);
            setSeq(idx);
        };
        function onDeleteSeq(idx:number,it:any){
            inp?.测厚表?.splice(idx,1);
            setInp({...inp,测厚表: [...inp?.测厚表] });
            setSeq(null);
        };
        function onInsertSeq(idx:number,it:any){
            inp?.测厚表?.splice(idx,0, obj);
            setInp({...inp,测厚表:[...inp?.测厚表] });
            setSeq(idx);
        };
        function onAddSeq(idx:number){
            let size =inp?.测厚表?.push(obj);
            setInp( (inp?.测厚表&&{...inp,测厚表:[...inp?.测厚表] } )  || {...inp,测厚表:[obj] } );
            setSeq((inp?.测厚表&&(size-1))  || 0 );
        };

        const editor=<Layer elevation={"sm"} css={{ padding: '0.25rem' }}>
            <div>
                <LineColumn  column={2}>
                    <InputLine label={`测点1编号`}>
                        <Input   value={obj.no1 ||''}   onChange={e =>setObj({...obj, no1: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl1 ||''}   onChange={e =>setObj({...obj, vl1: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点2编号`}>
                        <Input   value={obj.no2 ||''}   onChange={e =>setObj({...obj, no2: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl2 ||''}   onChange={e =>setObj({...obj, vl2: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点3编号`}>
                        <Input   value={obj.no3 ||''}   onChange={e =>setObj({...obj, no3: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl3 ||''}   onChange={e =>setObj({...obj, vl3: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点4编号`}>
                        <Input   value={obj.no4 ||''}   onChange={e =>setObj({...obj, no4: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl4 ||''}   onChange={e =>setObj({...obj, vl4: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点5编号`}>
                        <Input   value={obj.no5 ||''}   onChange={e =>setObj({...obj, no5: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl5 ||''}   onChange={e =>setObj({...obj, vl5: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点6编号`}>
                        <Input   value={obj.no6 ||''}   onChange={e =>setObj({...obj, no6: e.currentTarget.value} ) } />
                    </InputLine>
                    <InputLine label={`测点厚度`}>
                        <Input   value={obj.vl6 ||''}   onChange={e =>setObj({...obj, vl6: e.currentTarget.value} ) } />
                    </InputLine>
                </LineColumn>
                <Button onPress={() => {
                    if(seq !== null) {
                        inp?.测厚表?.splice(seq, 1, obj);
                        setInp({ ...inp, 测厚表: [...inp?.测厚表] });
                    }
                    else setInp({ ...inp, 测厚表: [obj] });
                } }
                >{inp?.测厚表?.length>0? `改一组就确认`: `新增一组`}</Button>
            </div>
        </Layer>;

        const instrumentTable=<div>
            {inp?.测厚表?.map((a:any,i:number)=>{
                return <React.Fragment  key={i}>
                    <div>{`${i+1}`}
                        <Popover>
                            <PopoverRefer css={{width: '-webkit-fill-available',maxWidth: '40rem' }}>
                                <ButtonRefComp  size="md" variant="ghost"  css={{ flexWrap: 'wrap',
                                        width: '-webkit-fill-available', justifyContent: 'space-between',
                                        height: 'unset', minHeight: '32px', padding: 'unset' }}>
                                    <Text>{a.no1??''}:{a.vl1||'/'},</Text>
                                    <Text>{a.no2??''}:{a.vl2||'/'},</Text>
                                    <Text>{a.no3??''}:{a.vl3||'/'},</Text>
                                    <Text>{a.no4??''}:{a.vl4||'/'},</Text>
                                    <Text>{a.no5??''}:{a.vl5||'/'},</Text>
                                    <Text>{a.no6??''}:{a.vl6||'/'}</Text>
                                </ButtonRefComp>
                            </PopoverRefer>
                            <PopoverContent>
                                <PopoverDescription>
                                    <MenuList>
                                        <MenuItem onPress={()=>onModifySeq(i,a)}>修改</MenuItem>
                                        <MenuItem onPress={()=>onDeleteSeq(i,a)}>刪除这条</MenuItem>
                                        <MenuItem onPress={()=>onInsertSeq(i,a)}>插入一条</MenuItem>
                                        <MenuItem onPress={()=>onAddSeq(i)}>末尾新增一条</MenuItem>
                                    </MenuList>
                                </PopoverDescription>
                                <PopoverClose>
                                    <IconX/>
                                </PopoverClose>
                            </PopoverContent>
                        </Popover>
                    </div>
                    {i===seq && editor}
                </React.Fragment>;
            }) }
        </div>;

        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}  redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'壁厚测定-测厚记录'}>
                <Text  variant="h5">
                测 厚 记 录 （ 测点厚度单位：㎜）；
                </Text>
                按照每一行布局6个测厚点为一组方式录入的，允许某些方格空缺:
                <hr/>
                {instrumentTable}
                {seq===null && editor}
            </InspectRecordLayout>
        );
    } );
